# coding=UTF-8
import datetime
import json
import os
import time

import requests

from common import KLineEnum
from common.StockDict import stock_dict
from common.utils import DateUtil, JsonUtil, DocUtil

# 返回当前工作目录
base_path = os.getcwd()
stock_day_k_path = base_path.split('\\stock')[0] + '\\stock\\day_k\\'


# day_k_result 逆序 时间最新再最前 不包含当天的k线 获取最新的几条数据
# stock_code:股票代码；size: 查询条数
def day_k_local_previous(stock_code, size):
    file_path = stock_day_k_path + stock_code + '.txt'
    mkdir(stock_day_k_path, stock_code)
    day_k_file = open(file_path, mode='r', encoding='utf-8')
    day_k_results = []
    one_day = day_k_file.readline()
    print(one_day)
    if not one_day:
        day_k_results = update_day_k_local(stock_code)
        day_k_file.close()
    else:
        one_day_k = JsonUtil.info_to_json(day_k_file.readline()[:-1])
        day_k_file.close()
        u_day = int(one_day_k['rq'][-2:])
        t_day = datetime.datetime.now().day
        if u_day != t_day:  # 不是当天时间更新
            day_k_results = update_day_k_local(stock_code)[0:size + 1]
        # 是最新的日期
        if len(day_k_results) == 0:
            # 读取文档中内容
            day_k_results = DocUtil.get_path_doc_info(file_path)[1:size + 2]
        day_ = JsonUtil.info_to_json(day_k_results[0])
        rq = int(day_['rq'][-2:])  # 2020-11-24
        if t_day == rq:
            day_k_results = day_k_results[1:size + 1]
        else:
            day_k_results = day_k_results[0:size]
    return day_k_results


# 更新本地日k
def update_day_k_local(stock_code):
    day_k_results = []
    day_k_file = open(stock_day_k_path + stock_code + '.txt', mode='w', encoding='utf-8')
    today = DateUtil.get_date_time()
    if today.hour >= 15:
        today = DateUtil.add_day(today, 1)
        today_str = DateUtil.date_to_str(today, '%Y-%m-%d')
        today_str += " 09:20:00"
        today = DateUtil.str_to_date(today_str, '%Y-%m-%d %H:%M:%S')
    stock_info = {'up_time': str(round(time.mktime(today.timetuple())))}
    day_k_file.write(str(stock_info).replace('\'', '\"') + '\n')
    stock = stock_dict[stock_code]
    # 获取k线
    k_lines = day_k(stock_code, stock['name'])
    k_lines_l = len(k_lines)
    for i in range(k_lines_l):
        # kline_arr = k_lines[k_lines_l - i - 1].split(',')
        day_k_results.append(KLineEnum.Stock.format_k_line(k_lines[k_lines_l - i - 1]))
        day_k_file.write(str(KLineEnum.Stock.format_k_line(k_lines[k_lines_l - i - 1])).replace('\'', '\"') + '\n')
    day_k_file.close()
    return day_k_results


# 日k，默认大小120
def day_k(stock_code, stock_name):
    return day_k_size(stock_code, stock_name, 120)


'''
日线
stock_code: 股票代码
stock_name: 股票名称
size: 查询条数
'''


def day_k_size(stock_code, stock_name, size):
    # print("获取日K,股票编码" + stock_code + '其他信息' + stock_name)
    time_stamp = int(round(time.time() * 1000))
    path_url = 'http://66.push2his.eastmoney.com/api/qt/stock/kline/get?cb=jQuery1124015253095575263576_' \
               + str(time_stamp) + '&secid=' + ('1' if str.startswith(stock_code, '6') else '0') + '.' \
               + str(stock_code) + \
               '&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5' \
               '&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58&klt=101' \
               '&fqt=0&end=20500101&lmt=' + str(size) + '&_=' + str(time_stamp)
    # print(path_url)
    resp = requests.get(path_url)
    resp_content = str(resp.content.decode('utf-8'))
    if resp_content == '':
        print("\033[32m$$$$$$$$$$$$$$$$$获取日K线地址" + path_url + "不能使用$$$$$$$$$$$$$$$\033[0m")
    days_info_str = resp_content.split('(')[1].split(')')[0]
    resp_json = json.loads(days_info_str)
    k_lines = resp_json['data']['klines']
    # record_day_k_local(stock_code, k_lines)
    return k_lines


# 记录日k到本地
def record_day_k_local(code, k_lines):
    today = DateUtil.get_date_time()
    if today.hour >= 14:
        today = DateUtil.add_day(today, 1)
        today_str = DateUtil.date_to_str(today, '%Y-%m-%d')
        today_str += " 08:20:00"
        today = DateUtil.str_to_date(today_str, '%Y-%m-%d %H:%M:%S')
    else:  # 不到时间不进行更新提高速度
        return
    day_k_file = open(stock_day_k_path + code + '.txt', mode='w', encoding='utf-8')
    stock_info = {'up_time': str(round(time.mktime(today.timetuple())))}
    day_k_file.write(str(stock_info).replace('\'', '\"') + '\n')
    k_lines_l = len(k_lines)
    for i in range(k_lines_l):
        day_k_file.write(str(KLineEnum.Stock.format_k_line(k_lines[k_lines_l - i - 1])).replace('\'', '\"') + '\n')
    day_k_file.close()


# 创建文件夹
def mkdir(self, file_name):
    if not os.path.exists(self):
        os.makedirs(self)
        os.open(self + file_name + '.txt', mode='w')
        os.close(self)


if __name__ == '__main__':
    stock_code = '603738'
    day_k_result = day_k_local_previous(stock_code, 5)
    record_day_k_local(stock_code, day_k_result)
    print(day_k_result)
